<template>
  <div class="app-container">
    <custom-container ref="customContainerRef" :ref="getChildList" :config="mainConfig" />
    <!-- 上传价格表 -->
    <Upload
      ref="fileUpload"
      name="file"
      import-url="/system/customer/price"
      @getList="handleQuery"
    />
    <!-- 更新价格表 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      append-to-body
      title="更新价格表"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx,.xls"
        :headers="upload.headers"
        :http-request="handleUpload"
        action="#"
        :disabled="upload.isUploading"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖入此处,或
          <em>点击上传</em>
        </div>
      </el-upload>
      <template #footer>
        <div>
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="historyOpen"
      :close-on-click-modal="false"
      append-to-body
      title="历史价格"
      class="historyPrice"
    >
      <el-table v-loading="historyLoading" :data="historyTableList">
        <el-table-column
          label="价格表名称"
          prop="name"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建人"
          prop="createUser"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          prop="createTime"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="状态"
          :auto-formatter="(row) => (DictDirection.系统显示隐藏, row.status)"
          prop="status"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { Delete, Refresh, Plus, Download, Edit, Document, Eleme, UploadFilled } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, defineAsyncComponent, computed } from 'vue'
import { ElMessage, ElMessageBox, ElButton, ElSwitch } from 'element-plus'
import { DictDirection } from '@/store/modules/dicts'
import { getToken, getTokenType } from '@/utils/auth'
import { customerPriceList, editCustomerPrice, deleteCustomerPrice, updateStatus } from '@/api/customer/priceManage'

const Upload = defineAsyncComponent(() => import('./compontents/setUploadForm.vue'))
const tokenType = getTokenType()
let // 选中数组
  ids = [],
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  // 日期范围
  dateRange = ref([]),
  // 当前选中的id
  currentId = ref(null),
  // 更新价格表
  open = ref(false),
  // 历史价格
  historyLoading = ref(false),
  historyOpen = ref(false),
  historyTableList = ref([]),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: '1',
  }),
  // loading加载
  loadingUpload = ref(false),
  // 文件上传
  upload = ref({
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: `${ tokenType }${ getToken() }` },
    url: `${ import.meta.env.VITE_BASE_API }`,
  }),
  // 导入文件
  fileUpload = ref(null),
  formData = ref(null),
  customContainerRef = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $download2 },
      },
    },
  } = getCurrentInstance()
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
// 2、父组件中定义和ref同名的变量
const getChildList = ref(null)
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.id)
  console.log(ids)
  // single.value = rows.length != 1;
  multiple.value = !rows.length
}
// 导入价格
const handleAdd = () => {
  fileUpload.value.open = true
}
// 修改价格
const handleUpdate = (row: { [key: string]: any }) => {
  const currentId = row?.id || ids
  console.log(currentId)
  open.value = true
}
// 删除
const handleDelete = (row: { [key: string]: any }) => {
  const id = (row && row.id) || ids
  console.log(id)
  ElMessageBox.confirm(`是否确认删除编号为"${ id }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => deleteCustomerPrice({ data: row }))
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((err) => {
    if (err == 'cancel') {
      ElMessage.info('取消删除')
    }
  })
}
// 下载价格
const handleImport = (row: { [key: string]: any }) => {
  const name = row.name
  if (name != null) {
    const index = name.lastIndexOf('.')
    let newName = ''
    if (index != -1) {
      newName = name.substring(0, index)
    } else {
      newName = name
    }
    row.downLoading = true
    const rowList = JSON.stringify(row)
    loadingUpload.value = true
    row = $download2('/system/customer/price/download', { data: rowList }, `${ newName + new Date().getTime() }.xlsx`).then((res) => {
      row.downLoading = false
    })
  }
}
// 历史价格
const handleHistory = (row: { [key: string]: any }) => {
  historyLoading.value = true
  historyOpen.value = true
  customerPriceList({ parentId: row.id })
  .then((res) => {
    if (res.code == 200) {
      historyTableList.value = res.rows
      historyLoading.value = false
    }
  })
  .catch((err) => {
    console.log(err)
    historyLoading.value = false
  })
}
// 文件更新成功
const { proxy } = getCurrentInstance() as any
const handleFileSuccess = (res) => {
  open.value = false
  upload.value.isUploading = false
  proxy.$refs.upload.clearFiles()
  ElMessageBox.alert(res.msg, '导入结果', { dangerouslyUseHTMLString: true })
}
const handleFileError = () => {
  proxy.upload.isUploading = false
  proxy.$refs.upload.clearFiles()
  proxy.$alert('异常导入')
}
// 文件自定义上传
const handleUpload = async (params) => {
    const { file } = params
    const formData = new FormData()
    formData.append('file', file.file)
  },
  submit = () => {
    upload.value.isUploading = true
    formData.value = new FormData()
    proxy.$refs.upload.submit()
    formData.value.vale.append('id', currentId.value)
    editCustomerPrice(formData.value)
    .then((res) => {
      if (res.code == 200) {
        handleFileSuccess(res)
        return
      }
      handleFileError()
    })
    .catch((err) => {
      console.log(err)
      handleFileError()
    })
  }
// 改变状态
const handleStatusChange = (row: { [key: string]: any }, val) => {
  updateStatus({ id: row.id, status: val })
  .then((res) => {
    if (res.code == 200) {
      return
    }
    row.status = Number(!val)
  })
  .catch((err) => {
    console.log(err)
    row.status = Number(!val)
  })
}
// 主体配置
const mainConfig = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '价格表名称',
            prop: 'name',
            minWidth: '300',
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            option: {
              dictInfo: { dict: DictDirection.通用状态 },
            },
          },
        ],
        queryParams: queryParams.value,
        formOption: {
          labelWidth: '68px',
        },
      },
      btns: [
        {
          title: '导入价格',
          icon: Plus,
          type: 'primary',
          onClick: handleAdd,
        },
        {
          title: '修改价格',
          icon: Delete,
          type: 'warning',
          onclick: handleUpdate,
          disabled: multiple.value,
        },
        {
          title: '删除',
          icon: Delete,
          type: 'danger',
          onClick: handleDelete,
          disabled: multiple.value,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55', align: 'center' },
          {
            label: 'id',
            prop: 'id',
            minWidth: '20',
          },
          {
            label: '价格表名称',
            prop: 'name',
            minWidth: '100',
          },
          {
            label: '创建人',
            prop: 'createUser',
            minWidth: '100',
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            minWidth: '100',
          },
          {
            label: '状态',
            prop: 'status',
            minWidth: '60',
            autoFormatter: {
              dict: DictDirection.通用状态,
              rowKey: 'status',
            },
          },
          {
            label: '操作',
            fixed: 'right',
            showOverflowTooltip: false,
            minWidth: '200',
            render: (h, params) => {
              const buttons = [
                {
                  title: '下载',
                  clickFun: handleImport,
                  loading: 'loadingUpload',
                },
                {
                  title: '修改',
                  clickFun: handleUpdate,
                },
                {
                  title: '删除',
                  clickFun: handleDelete,
                },
                {
                  title: '历史价格',
                  clickFun: handleHistory,
                  render(h, params) {
                    return h(ElSwitch, {
                      onChange: (val) => {
                        handleStatusChange(params.row, val)
                        console.log('handleStatusChange', params)
                      },
                      modelValue: params.row.status,
                      'onUpdate:modelValue': (value) => {
                        // emit('update:modelValue', value);
                      },
                      activeValue: '0',
                      inactiveValue: '1',
                      activeColor: '#C0CCDA',
                      inactiveColor: '#409EFF',
                    })
                  },
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleSelectionChange(rows)
          },
        },
      },
      api: customerPriceList,
    }
  },
  set(val) {
    return val
  },
})
</script>
<style lang="less" scoped>
.historyPrice {
}
</style>
